package com.gmscosmo.janus.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

/**
 * @author stephen.qiu
 */
@Component
public class ServerSingleton {
    private EventLoopGroup mainGroup;
    private EventLoopGroup subGroup;
    private ServerBootstrap serverBootstrap;
    private ChannelFuture future;
    @Autowired
    ServerInitializer serverInitializer;
    @Resource(name = "ThreadPoolTaskExecutor")
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    public ServerSingleton() {
        //mainGroup用来处理连接
        mainGroup = new NioEventLoopGroup(2);
        //subGroup用来处理后续事件
        subGroup = new NioEventLoopGroup();
        serverBootstrap = new ServerBootstrap();
    }

    @PostConstruct
    public void init() {
        serverBootstrap.group(mainGroup, subGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(serverInitializer);
        start();
    }

    /**
     * 绑定端口
     * 当这个方法执行后，ServerBootstrap就可以接受指定端口上的socket连接了。
     * 一个ServerBootstrap可以绑定多个端口
     *
     * @return null
     */
    public Channel bind() throws InterruptedException {
        return serverBootstrap.bind(8888).sync().channel();
    }

    @PreDestroy
    public void stop() {
        mainGroup.shutdownGracefully();
        subGroup.shutdownGracefully();
    }

    //这个才是入口程序，走start()操作
    public void start() {
        try {
            future = this.bind().closeFuture();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("启动 WebSocket 成功");
    }
}